class Folder {
    constructor(name) {
        this.name = name;
        this.parent = null;
        this.files = [];
    }

    add(file) {
        file.parent = this;
        this.files.push(file);
    }

    scan() {
        console.log(`开始扫描文件夹：${this.name}`);
        this.files.forEach(file => file.scan());
    }

    remove() {
        if (!this.parent) {
            return;
        }
        for (let i = 0, files = this.parent.files; i < files.length; i++) {
            if (this === files[i]) {
                files.splice(i, 1);
            }
        }
    }
}

class File {
    constructor(name) {
        this.name = name;
        this.parent = null;
    }

    add() {
        throw new Error('文件下面不能再添加文件');
    }

    scan() {
        console.log(`开始扫描文件：${this.name}`);
    }

    remove() {
        if (!this.parent) {
            return;
        }
        for (let i = 0, files = this.parent.files; i < files.length; i++) {
            if (this === files[i]) {
                files.splice(i, 1);
            }
        }
    }
}

// test
let folder = new Folder('学习资料');
let folder1 = new Folder('HTML');
let folder2 = new Folder('JavaScript');

let file1 = new File('HTML宝典');
let file2 = new File('JavaScript 设计模式');
let file3 = new File('数据结构与算法');

folder1.add(file1);
folder2.add(file2);

folder.add(folder1);
folder.add(folder2);
folder.add(file3);

folder.scan();

console.log('============== 测试移除文件或文件夹 ==============');

file3.remove();
folder1.remove();
folder.scan();
